import 'dart:async';
import 'dart:ui';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_edit_with_title_dialog/common_edit_with_title_dialog.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/media_library/media_library_index/bean/media_library_index_response_bean.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/media_change_interval_event.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/media_library_index_refresh_even.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/terminal_num_update_event.dart';
import 'package:e_reception_flutter/media_library/media_library_index/media_library_index_page.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/poster_detail_page.dart';
import 'package:e_reception_flutter/singleton/constant_repository/constant_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail/terminal_detail_view_model.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/common_select_util.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_date_time_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_menu_widget/click_back_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_menu_widget/menu_dialog.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

import '../media_library_index_played_view_model.dart';
import '../media_library_index_playing_view_model.dart';
import '../media_library_index_view_model.dart';
import '../media_library_index_wait_play_view_model.dart';
import 'media_detail_page.dart';

/// 媒体库已播
class MediaLibraryPlayPage extends StatefulWidget {

  static final String TYPE_PLAYED = "type_played";
  static final String TYPE_PLAYING = "type_playing";
  static final String TYPE_WAIT_PLAY = "type_wait_play";

  final String pageType;
  final String gps;

  const MediaLibraryPlayPage({Key key, this.pageType, this.gps})
      : super(key: key);

  @override
  _MediaLibraryPlayPageState createState() => _MediaLibraryPlayPageState();
}

class _MediaLibraryPlayPageState extends BasePagerState<MediaLibraryIndexListItemBean, MediaLibraryPlayPage>{
  BasePagerViewModel _viewModel;
  MediaLibraryIndexViewModel _indexViewModel;
  StreamSubscription _streamSubscription;
  StreamSubscription _mediaLibraryStreamSubscription;
  StreamSubscription _terminalNumRefreshSubscription;
  int _allTerminalSize = 0;
  int _changeInterval = 15;
  String _splicingPoster = "00";
  @override
  void initState() {
    super.initState();
    _indexViewModel = MediaLibraryIndexViewModel(this);
    if(MediaLibraryPlayPage.TYPE_PLAYED == widget?.pageType){
      _viewModel = MediaLibraryIndexPlayedViewModel(this);
    }else if(MediaLibraryPlayPage.TYPE_PLAYING == widget?.pageType){
      _viewModel = MediaLibraryIndexPlayingViewModel(this);
      _indexViewModel.getMediaChangeInterval(context);
    }else if(MediaLibraryPlayPage.TYPE_WAIT_PLAY == widget?.pageType){
      _viewModel = MediaLibraryIndexWaitPlayViewModel(this);
    }

    _viewModel.refresh();
    _streamSubscription =
        VgEventBus.global.on<MediaLibraryRefreshEven>()?.listen((event) {
          _viewModel.refresh();
        });
    _mediaLibraryStreamSubscription =
        VgEventBus.global.on<MonitoringMediaLibraryIndexClass>()?.listen((event) {
          _viewModel.refresh();
        });
    _terminalNumRefreshSubscription = VgEventBus.global.streamController.stream.listen((event) {
      if(event is TerminalNumRefreshEvent){
        if((event?.num??0) != 0 && _allTerminalSize == event?.num){
          //数量不变
          print("终端数量未变，不执行");
          return;
        }
        _allTerminalSize = event?.num??0;
        _viewModel.refresh();
      }
      if(event is MediaChangeIntervalEvent){
        if((event?.interval??0) != 0 && _changeInterval == event?.interval){
          //数量不变
          print("切换间隔未变，不执行");
        }else{
          setState(() {
            _changeInterval = event?.interval??15;
          });
        }
        if(StringUtils.isNotEmpty(event?.splicing??"") && ((_splicingPoster??"") == (event?.splicing??""))){
          print("拼合地址未变，不执行");
        }else{
          setState(() {
            _splicingPoster = event?.splicing??"00";
          });
        }
      }
    });
  }

  @override
  void dispose() {
    _terminalNumRefreshSubscription?.cancel();
    _streamSubscription?.cancel();
    _mediaLibraryStreamSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _indexViewModel = MediaLibraryIndexViewModel(this);
    return  VgPlaceHolderStatusWidget(
        emptyOnClick: () => _viewModel?.refresh(),
        errorOnClick: () => _viewModel.refresh(),
        loadingStatus: data == null,
        // emptyStatus: data?.length == 0 && (MediaLibraryPlayPage.TYPE_PLAYING != widget?.pageType),
        emptyStatus: data?.length == 0,
        child: VgPullRefreshWidget.bind(
            state: this, viewModel: _viewModel, child: SingleChildScrollView(
          child:                 _toGridWidget(),
        ))
    );
  }

  Widget _toGridWidget(){
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        (MediaLibraryPlayPage.TYPE_PLAYING == widget?.pageType)?_toSetChangeIntervalWidget():SizedBox(height: 9,),
        GridView.builder(
          padding: EdgeInsets.only(
              left: 15,
              right: 15,
              top: 3,
              bottom: getNavHeightDistance(context)
          ),
          itemCount: data?.length ?? 0,
          physics: BouncingScrollPhysics(),
          shrinkWrap: true,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            mainAxisSpacing: 5,
            crossAxisSpacing: 5,
            childAspectRatio: 1 / 1.2,
          ),
          itemBuilder: (BuildContext context, int index) {
            return _toGridItemWidget(context, data?.elementAt(index));
          },
        ),
      ],
    );
  }

  Widget _toSetChangeIntervalWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        return SelectUtil.showListSelectDialog(
            context: context,
            title: "图片切换时间",
            positionStr: "${_changeInterval}秒",
            textList: ConstantRepository.of().getMediaChangeInterval(),
            onSelect: (dynamic value) {
              _changeInterval = int.parse(value.toString().replaceAll("秒", ""));
              setState(() {});
              _indexViewModel.updateMediaChangeInterval(context, _changeInterval);
            }
        );
      },
      child: Container(
        height: 35,
        padding: EdgeInsets.symmetric(horizontal: 15),
        alignment: Alignment.centerLeft,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              "图片切换时间：",
              style: TextStyle(
                color: ThemeRepository.getInstance().getTextBFC2CC_BFC2CC(),
                fontSize: 12,
              ),
            ),
            Text(
              "${_changeInterval}秒",
              style: TextStyle(
                color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                fontSize: 12,
              ),
            ),
            SizedBox(width: 3,),
            Image.asset(
              "images/icon_change_interval.png",
              width: 7,
            ),
            Spacer(),
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: (){
                _splicingPoster = (_splicingPoster == "00")?"01":"00";
                setState(() {});
                _indexViewModel.updateSplicingPosterStatus(context, _splicingPoster);
              },
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 4),
                    child: Image.asset(
                      (_splicingPoster == "00"
                          ? "images/common_selected_ico.png"
                          : "images/common_unselect_ico.png"),
                      height: 14,
                    ),
                  ),
                  Text(
                    "智能海报拼合地址",
                    style: TextStyle(
                      color: ThemeRepository.getInstance().getTextBFC2CC_BFC2CC(),
                      fontSize: 12,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }


  Map<String,ValueChanged> _getMenuMap(BuildContext context,MediaLibraryIndexListItemBean itemBean){
    return {
      "重命名":(_){
        _onUpdateName(itemBean);
      },
      "删除文件":(_){
        _onDelete(itemBean);
      }
    };
  }

  Widget _toGridItemWidget(BuildContext context, MediaLibraryIndexListItemBean itemBean) {
    double containerHeight = ((ScreenUtils.screenW(context) - 15 - 15) / 3);
    double width = ((((ScreenUtils.screenW(context) - 15 - 15) / 3) * 9) / 16);
    double height = 0;
    //不是16/9的图要重新布局
    bool resizeFlag = false;
    if (!StringUtils.isEmpty(itemBean?.picsize)) {
      List<String> sizeList = itemBean?.picsize?.split("*");
      int x = int.parse(sizeList[0]);
      int y = int.parse(sizeList[1]);
      double scale = x/y;
      height = width/scale;
      resizeFlag = true;
    }
    //是否需要模糊
    bool needBlurFlag = (containerHeight - height).abs() > 50;

    return ClickBackgroundWidget(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        _onTap(itemBean);
      },
      onLongPress: (detail){
        return MenuDialogUtils.showMenuDialog(context: context,longPressDetails: detail,itemMap: _getMenuMap(context,itemBean));
      },
      child: Column(
        children: <Widget>[
          ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: AspectRatio(
              aspectRatio: 1,
              child: Container(
                color: Colors.black,
                child: Stack(
                  alignment: Alignment.center,
                  children: <Widget>[
                    ((resizeFlag??false) && needBlurFlag)?
                    Stack(
                      alignment: Alignment.center,
                      children: [
                        // Container(
                        //     width: width,
                        //     height: containerHeight,
                        //     child: VgCacheNetWorkImage(
                        //       itemBean?.getCoverUrl() ?? "",
                        //       imageQualityType: ImageQualityType.middleDown,
                        //     )
                        // ),
                        // Container(
                        //   width: width,
                        //   height: containerHeight,
                        //   child: BackdropFilter(
                        //     filter: new ImageFilter.blur(sigmaX: 0, sigmaY: 5),
                        //     child: new Container(
                        //       // color: Colors.white.withOpacity(0.2),
                        //       color: Color(0x33FFFFFF).withOpacity(0.2),
                        //       width: width,
                        //       height: containerHeight,
                        //     ),
                        //   ),
                        // ),
                        Container(
                            width: width,
                            height: height,
                            child: VgCacheNetWorkImage(
                              itemBean?.getCoverUrl() ?? "",
                              imageQualityType: ImageQualityType.middleDown,
                            )
                        ),
                      ],
                    ):VgCacheNetWorkImage(
                      itemBean?.getCoverUrl() ?? "",
                      imageQualityType: ImageQualityType.middleDown,
                    ),
                    Positioned(
                      top: 5,
                      left: 5,
                      child: Offstage(
                        offstage: MediaLibraryPlayPage.TYPE_PLAYING != widget?.pageType,
                        child: Container(
                          width: 5,
                          height: 5,
                          decoration: BoxDecoration(
                              color: ThemeRepository.getInstance()
                                  .getMinorRedColor_F95355(),
                              shape: BoxShape.circle),
                        ),
                      ),
                    ),
                    Offstage(
                      offstage: !(itemBean?.isVideo() ?? false),
                      child: Opacity(
                        opacity: 0.5,
                        child: Image.asset(
                          "images/video_play_ico.png",
                          width: 40,
                        ),
                      ),
                    ),
                    Positioned(
                      top: 0,
                      right: 0,
                      child: Offstage(
                        offstage: !(itemBean?.isVideo() ?? false),
                        child: Container(
                          width: 33,
                          height: 14,
                          decoration: BoxDecoration(
                              color: VgColors.INPUT_BG_COLOR,
                              borderRadius: BorderRadius.only(
                                  bottomLeft: Radius.circular(4),
                                  topRight: Radius.circular(4))),
                          child: Center(
                            child: Text(
                              VgDateTimeUtils.getSecondsToMinuteStr(itemBean?.videotime) ?? "00:00",
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 9,
                                  height: 1.2
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          Expanded(
            child: Container(
              margin: const EdgeInsets.symmetric(vertical: 4),
              alignment: Alignment.topLeft,
              child: Text(
                // ("永久播放" == (itemBean?.getResumePlayInterval()??"剩余0天"))?"永久播放"
                //     :("已播放${itemBean?.getAlreadyPlayInterval()??"0天"}，${itemBean?.getResumePlayInterval()??"剩余0天"}"),
                itemBean?.getPlayTimeString(pageType: widget?.pageType??""),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: ThemeRepository.getInstance()
                      .getTextMinorGreyColor_808388(),
                  fontSize: 9,
                ),
              ),
            ),
          )
        ],
      ),
    );
  }


  void _onTap(MediaLibraryIndexListItemBean itemBean) {
    if (itemBean == null) {
      return null;
    }
    if(itemBean.isHtml()){
      PosterDetailPage.navigatorPush(context, itemBean.htmlurl, itemBean.id,
          itemBean.likeflg, itemBean.cretype, "",  true,
          itemBean.logoflg, itemBean.addressflg, itemBean.diyflg, "02",
          itemBean.addressdiy, itemBean.namediy, itemBean.logodiy,
          itemBean.splpicurl, itemBean.pictype, gps: widget?.gps);
    }else{
      MediaDetailPage.navigatorPush(context, itemBean?.id, "02");
    }
  }

  void _onDelete(MediaLibraryIndexListItemBean itemBean) async {
    if (StringUtils.isEmpty(itemBean?.id)) {
      VgToastUtils.toast(context, "资源获取失败");
      return;
    }
    bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
        title: "提示",
        content: "所有终端显示屏中该文件都会删除，且不可找回，确认继续？",
        cancelText: "取消",
        confirmText: "删除",
        confirmBgColor:
        ThemeRepository.getInstance().getMinorRedColor_F95355());
    if (result ?? false) {
      if("01" == (itemBean?.uploadflg??"")){
        //删除推送海报
        _indexViewModel.deleteMediaPushPoster(context, itemBean.id, callback: (){
          _viewModel.refresh();
        });
      }else{
        _indexViewModel?.deleteFolder(context, itemBean.id, itemBean?.videoid, itemBean?.getToDeletePicUrl(),
            (itemBean?.isVideo()??false)?(itemBean?.picurl??""):"",
            callback: (){
              _viewModel.refresh();
            });
      }
    }
  }

  void _onUpdateName(MediaLibraryIndexListItemBean itemBean) {
    if (StringUtils.isEmpty(itemBean?.id)) {
      VgToastUtils.toast(context, "资源获取失败");
      return;
    }
    CommonEditWithTitleDialog.navigatorPushDialog(context,
        title: "重命名",
        confirmText: "确定",
        oldContent: itemBean.picname,
        onConfirm: (String content, VoidCallback popCallBack) {
          if (StringUtils.isEmpty(content)) {
            VgToastUtils.toast(context, "文件名不能为空");
            return;
          }
          VgToolUtils.removeAllFocus(context);
          _indexViewModel?.updateFolderName(context, itemBean?.id,
              content, popCallBack, callback: (){
                _viewModel.refresh();
              });
        });
  }
}
